﻿using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NChainer;
using NConstrictor;
//using Real = System.Double;
using Real = System.Single;

namespace KelpNet.Tests
{
    [TestClass]
    public class TestEmbedID
    {
        [TestMethod]
        public void EmbedIDRandomTest()
        {
            Python.Initialize();
            Chainer.Initialize();

            int inputCount = Mother.Dice.Next(2, 30);
            int outputCount = Mother.Dice.Next(1, 30);
            int batchCount = Mother.Dice.Next(1, 5);

            int[,] input = (int[,])Enumerable.Repeat(0, batchCount * inputCount).ToNdArray(batchCount, inputCount);
            input[0, 0] = 1;

            Real[,,] dummyGy = Initializer.GetRandomValues<Real[,,]>(batchCount, inputCount, outputCount);
            Real[,] w = Initializer.GetRandomValues<Real[,]>(inputCount, outputCount);

            //Chainer
            NChainer.EmbedID<Real> cEmbedId = new NChainer.EmbedID<Real>(inputCount, outputCount, w);

            Variable<int> cX = new Variable<int>(input);

            Variable<Real> cY = cEmbedId.Forward(cX);
            cY.Grad = dummyGy;

            cY.Backward();


            //KelpNet
            EmbedID<Real> embedId = new EmbedID<Real>(inputCount, outputCount, w);

            NdArray<Real> x = new NdArray<Real>(input, asBatch: true);

            NdArray<Real> y = embedId.Forward(x)[0];
            y.Grad = dummyGy.Flatten();

            y.Backward();


            Real[] cYdata = ((Real[,,])cY.Data).Flatten();

            Real[] cWgrad = ((Real[,])cEmbedId.W.Grad).Flatten();

            //許容範囲を算出
            Real delta = 0.00001f;

            //y
            Assert.AreEqual(cYdata.Length, y.Data.Length);
            for (int i = 0; i < y.Data.Length; i++)
            {
                Assert.AreEqual(cYdata[i], y.Data[i], delta);
            }

            //W.grad
            Assert.AreEqual(cWgrad.Length, embedId.Weight.Grad.Length);
            for (int i = 0; i < embedId.Weight.Grad.Length; i++)
            {
                Assert.AreEqual(cWgrad[i], embedId.Weight.Grad[i], delta);
            }
        }
    }
}
